package com.qf.shiro2203.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){
     /* 1.anon: 匿名访问过滤器
        2. authc需要登录才可以访问的过滤器
        3.perms: 权限校验过滤器
        4.roles: 角色校验过滤器
        5.logout: 登出过滤器*/
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        //无需登录即可访问url     anon
        definition.addPathDefinition("/a.html","anon");
        definition.addPathDefinition("/user/login","anon");
        //需要登录才能访问    authc
        definition.addPathDefinition("/b.html","authc");
        // url需要当前用户拥有document:read权限才可以访问
        definition.addPathDefinition("/c.html","perms[document:read]");
        // 需要当前用户拥有admin角色才能访问
        definition.addPathDefinition("/d.html","authc,roles[admin]");
        //如下配置代表，/home.html 资源可以使用 免登录（RememberMe）cookie直接访问，user 代表 过滤器名字
        definition.addPathDefinition("/error","anon");
        definition.addPathDefinition("/home.html","user");

        //默认所有url都需要登录后才能访问，但是上面配置anon的url除外
       // definition.addPathDefinition("/**","authc");



        return definition;

    }
    @Bean
    public Realm realm(){

        CustomRealm customRealm = new CustomRealm();

        //设置密码处理方式
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();

        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(1024);
        /*盐（salt）在CustomRealm这里处理*/

        customRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        return customRealm;
    }
}
